import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../core/viewmodels/auth_viewmodel.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/utils/error_handler_extension.dart';
import '../../../shared/widgets/cached_avatar.dart';
import 'edit_profile_page.dart';

class ProfilePage extends StatelessWidget {
  const ProfilePage({super.key});

  /// 获取头像显示文本（用户名首字母，如果为空则返回 'U'）
  String _getAvatarText(String? username) {
    if (username == null || username.isEmpty) {
      return 'U';
    }
    return username.substring(0, 1).toUpperCase();
  }

  Future<void> _handleLogout(BuildContext context) async {
    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认退出'),
        content: const Text('确定要退出登录吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text(
              '退出',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );

    if (confirmed != true || !context.mounted) return;

    // 执行退出
    final viewModel = context.read<AuthViewModel>();
    await viewModel.logout();

    if (!context.mounted) return;

    // 退出成功后，跳转到登录页
    Navigator.of(context).pushNamedAndRemoveUntil(
      AppConstants.routeLogin,
      (route) => false, // 清除所有路由栈
    );

    // 显示退出成功提示
    context.showSuccess('已退出登录');
  }

  Widget _buildSection({
    required BuildContext context,
    required List<Widget> children,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: children,
      ),
    );
  }

  Widget _buildMenuItem({
    required BuildContext context,
    required IconData icon,
    required String title,
    String? subtitle,
    Color? iconColor,
    VoidCallback? onTap,
    Widget? trailing,
  }) {
    // 默认使用灰色图标，更符合大众审美
    final defaultIconColor = Colors.grey[700] ?? Colors.black87;
    final finalIconColor = iconColor ?? defaultIconColor;
    
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(16),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 16),
          child: Row(
            children: [
              Container(
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      finalIconColor.withOpacity(0.15),
                      finalIconColor.withOpacity(0.08),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Icon(
                  icon,
                  color: finalIconColor,
                  size: 22,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF1A1A1A),
                        letterSpacing: -0.2,
                      ),
                    ),
                    if (subtitle != null) ...[
                      const SizedBox(height: 4),
                      Text(
                        subtitle,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey[600],
                          fontWeight: FontWeight.w400,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ],
                ),
              ),
              if (trailing != null)
                trailing
              else
                Icon(
                  Icons.chevron_right,
                  color: Colors.grey[400],
                  size: 20,
                ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: AppBar(
        title: const Text('我的'),
        automaticallyImplyLeading: false,
        elevation: 0,
      ),
      body: SafeArea(
        bottom: false,
        child: Consumer<AuthViewModel>(
          builder: (context, viewModel, child) {
            final user = viewModel.currentUser;
            
            return SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              child: Column(
                children: [
                // 用户信息头部区域（现代渐变设计）
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        Theme.of(context).colorScheme.primary,
                        Theme.of(context).colorScheme.primaryContainer,
                      ],
                    ),
                  ),
                  child: Material(
                    color: Colors.transparent,
                    child: InkWell(
                      onTap: () async {
                        final result = await Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (context) => const EditProfilePage(),
                          ),
                        );
                        // 如果编辑成功，界面会自动更新（因为使用了 Consumer）
                      },
                      borderRadius: BorderRadius.circular(12),
                      child: Row(
                        children: [
                          // 头像
                          Stack(
                            clipBehavior: Clip.none,
                            children: [
                              Container(
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  border: Border.all(
                                    color: Colors.white.withOpacity(0.3),
                                    width: 2,
                                  ),
                                ),
                                child: CachedAvatar(
                                  imageUrl: user?.avatar,
                                  name: user?.username ?? 'U',
                                  size: 56,
                                  borderRadius: 8,
                                ),
                              ),
                              Positioned(
                                bottom: -2,
                                right: -2,
                                child: Container(
                                  width: 22,
                                  height: 22,
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color: Theme.of(context).colorScheme.primary,
                                      width: 2,
                                    ),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black.withOpacity(0.15),
                                        blurRadius: 6,
                                        offset: const Offset(0, 2),
                                      ),
                                    ],
                                  ),
                                  child: Icon(
                                    Icons.camera_alt,
                                    size: 11,
                                    color: Theme.of(context).colorScheme.primary,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(width: 16),
                          // 用户信息
                          Expanded(
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  user?.nickname ?? user?.username ?? '未登录',
                                  style: const TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.white,
                                  ),
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                ),
                                // 只有当昵称和用户名都存在且不同时才显示用户名
                                if (user?.nickname != null && 
                                    user?.username != null && 
                                    user!.nickname != user!.username) ...[
                                  const SizedBox(height: 4),
                                  Text(
                                    user.username,
                                    style: TextStyle(
                                      fontSize: 13,
                                      color: Colors.white.withOpacity(0.8),
                                    ),
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 1,
                                  ),
                                ],
                              ],
                            ),
                          ),
                          Icon(
                            Icons.chevron_right,
                            color: Colors.white.withOpacity(0.8),
                            size: 20,
                          ),
                        ],
                      ),
                    ),
                  ),
                ),

                // 功能入口区域
                Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 账号信息
                    _buildSection(
                      context: context,
                      children: [
                        _buildMenuItem(
                          context: context,
                          icon: Icons.person_outline,
                          title: '个人信息',
                          subtitle: user?.email ?? '未设置邮箱',
                          iconColor: const Color(0xFF5B8DEF), // 主蓝色
                          onTap: () async {
                            final result = await Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (context) => const EditProfilePage(),
                              ),
                            );
                          },
                        ),
                        Divider(height: 1, indent: 74, endIndent: 16),
                        _buildMenuItem(
                          context: context,
                          icon: Icons.phone_outlined,
                          title: '手机号',
                          subtitle: user?.phone ?? '未绑定',
                          iconColor: const Color(0xFF5B8DEF), // 主蓝色
                          onTap: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(content: Text('手机号绑定功能开发中')),
                            );
                          },
                        ),
                        Divider(height: 1, indent: 74, endIndent: 16),
                        _buildMenuItem(
                          context: context,
                          icon: Icons.email_outlined,
                          title: '邮箱',
                          subtitle: user?.email ?? '未绑定',
                          iconColor: const Color(0xFF5B8DEF), // 主蓝色
                          onTap: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(content: Text('邮箱绑定功能开发中')),
                            );
                          },
                        ),
                      ],
                    ),

                    // 设置
                    _buildSection(
                      context: context,
                      children: [
                        _buildMenuItem(
                          context: context,
                          icon: Icons.settings_outlined,
                          title: '设置',
                          iconColor: const Color(0xFF5B8DEF), // 主蓝色
                          onTap: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(content: Text('设置功能开发中')),
                            );
                          },
                        ),
                        Divider(height: 1, indent: 74, endIndent: 16),
                        _buildMenuItem(
                          context: context,
                          icon: Icons.help_outline,
                          title: '帮助与反馈',
                          iconColor: const Color(0xFF5B8DEF), // 主蓝色
                          onTap: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(content: Text('帮助与反馈功能开发中')),
                            );
                          },
                        ),
                        Divider(height: 1, indent: 74, endIndent: 16),
                        _buildMenuItem(
                          context: context,
                          icon: Icons.info_outline,
                          title: '关于',
                          iconColor: const Color(0xFF5B8DEF), // 主蓝色
                          onTap: () {
                            showAboutDialog(
                              context: context,
                              applicationName: 'Violet IM',
                              applicationVersion: '1.0.0',
                              applicationIcon: Icon(
                                Icons.chat_bubble_outline,
                                size: 48,
                                color: Theme.of(context).colorScheme.primary,
                              ),
                            );
                          },
                        ),
                      ],
                    ),

                    // 退出登录
                    _buildSection(
                      context: context,
                      children: [
                          _buildMenuItem(
                            context: context,
                            icon: Icons.logout,
                            title: '退出登录',
                            iconColor: const Color(0xFFEF4444), // 错误红
                            onTap: () => _handleLogout(context),
                          trailing: viewModel.isLoading
                              ? const SizedBox(
                                  width: 20,
                                  height: 20,
                                  child: CircularProgressIndicator(strokeWidth: 2),
                                )
                              : null,
                        ),
                      ],
                    ),
                    
                    SizedBox(height: MediaQuery.of(context).padding.bottom + 20),
                  ],
                ),
              ],
            ),
          );
        },
      ),
      ),
    );
  }
}

